package com.seestech.sell.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.ValueFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;


/**
 * Created by idiot on 2017/7/20.
 */
public class JsonUtils {
    private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    /**
     * @description  json 过滤
     * @return
     */
    public static ValueFilter initValueFilter(final String ... params){
        //把long类型的转换为字符串
        ValueFilter valueFilter = new ValueFilter() {
            @Override
            public Object process(Object o, String name, Object value) {
                if(value instanceof Long){
                    return String.valueOf(value);
                }
                if(value instanceof Date){
                    return ((Date) value).getTime();
                }
                for (String param : params){
                    if(name.equals(param) && value == null){
                        return "";
                    }
                }
                return value;
            }
        };
        return valueFilter;
    }


    public static PropertyFilter initPropertyFilter(final String... ids){
        PropertyFilter propertyFilter = new PropertyFilter() {
            @Override
            public boolean apply(Object o, String name, Object value) {
                for (String id : ids){
                    if(name.equals(id)){
                        return false;
                    }
                }
                return true;
            }
        };
        return propertyFilter;
    }

    /**
     * @descripton   list -->  json 过滤之后的 jsonArray
     * @param list
     * @param params   设置过滤的属性  当null时返回空字符串
     * @return
     */
    public static JSONArray parseArray(List list, String ... params){
        //json过滤
        ValueFilter valueFilter = JsonUtils.initValueFilter(params);
        JSONArray object = JSON.parseArray(JSON.toJSONString(list, valueFilter));
        return object;
    }


    /**
     * @descripton   Object -->  json 过滤之后的 jsonObject
     * @param obj
     * @return
     */
    public static JSONObject parseObject(Object obj){
        //json过滤
        ValueFilter valueFilter = JsonUtils.initValueFilter();
        JSONObject object = JSON.parseObject(JSON.toJSONString(obj, valueFilter));
        return object;
    }
}
